package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 使用特定构造器实例化对象
 */
public class ReflectDemo3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Person p = new Person("李四");
        System.out.println(p);

        //1.获取类对象
        Class c = Class.forName("reflect.Person");
        /*
        2.通过类对象获取到对应的构造器
        Consteructor也是反射对象之一
        它的每一个实例仅表示一个构造器
         */
        //Constructor con = c.getConstructor(); //通过类对象获取Person的无参构造器
        // Person（String）
        Constructor con = c.getConstructor(String.class);
        Object obj = con.newInstance("王五"); //new  Person("王五");
        System.out.println(obj);

        //Person（String,int）
        Constructor con2 = c.getConstructor(String.class,int.class);
        Object obj2 = con2.newInstance("赵六", 20);//new Person("赵六",20);
        System.out.println(obj2);
    }
}
